package com.atguigu.gmall.payment.alipay.rest;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.constant.RabbitConstant;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.mq.service.RabbitService;
import com.atguigu.gmall.payment.alipay.confg.properties.AlipayProperties;
import com.atguigu.gmall.payment.alipay.service.AlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/payment/alipay")
@Slf4j
public class AlipayController {

    @Autowired
    AlipayService alipayService;

    @Autowired
    RabbitService rabbitService;


    @Autowired
    AlipayProperties alipayProperties;


    @GetMapping("/submit/{orderId}")
    public String getAlipayHtml(@PathVariable String orderId) throws AlipayApiException {
        String payHtml = alipayService.getAlipayHtml(Long.parseLong(orderId));
        return payHtml;
    }

    @PostMapping("/notify/success")
    public String success(@RequestParam Map<String, String> params) throws AlipayApiException {
        //回调以后需要验签，保证是支付宝回调的
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayProperties.getAlipayPublicKey(),
                alipayProperties.getCharset(),
                alipayProperties.getSignType()); //调用SDK验证签名

        log.info("json为：{}", JSONs.objecttoString(params));
        //验证通过才处理逻辑
        if (signVerified) {
            //验签通过，发送消息改变订单状态
            params.put("payment_way", "支付宝支付");
            rabbitService.sendMsg(RabbitConstant.EXCHANGE_ORDER_EVENT,RabbitConstant.RK_ORDER_PAYED,params);
            return "success";
        }else {
            log.info("疑是黑客攻击");
            return "error";
        }

    }
}
